import { Space } from 'antd';
import React from 'react';
import { useModel, SelectLang, setLocale } from 'umi';
import Avatar from './AvatarDropdown';
import styles from './index.less';
import ThemePopover from './ThemePopover';
import { isOpenFromPlatform } from '@/utils/env';

export type SiderTheme = 'light' | 'dark';

const GlobalHeaderRight: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  // function changeTheme(colorName: string) {
  //   let styleLink: HTMLLinkElement | null = document.getElementById(
  //     'theme-style',
  //   ) as HTMLLinkElement;
  //   if (styleLink) {
  //     styleLink.href = `./theme/${colorName}.css`;
  //   } else {
  //     styleLink = document.createElement('link');
  //     styleLink.type = 'text/css';
  //     styleLink.rel = 'stylesheet';
  //     styleLink.id = 'theme-style';
  //     styleLink.href = `./theme/${colorName}.css`;
  //     document.body.append(styleLink);
  //   }
  //   localStorage.setItem('themeData', colorName);
  // }
  function changeTheme(colorName: string, isLight: boolean) {
    // userSetting.current = {
    //   ...userSetting.current,
    //   primaryColor: theme.color
    // }
    // saveUserSetting(userSetting.current);
    // setInitState();
    console.log(isLight);
    let styleLink: HTMLLinkElement | null = document.getElementById(
      'theme-style',
    ) as HTMLLinkElement;
    let dxStyleLink: HTMLLinkElement | null = document.getElementById(
      'dx-theme-style',
    ) as HTMLLinkElement;

    if (styleLink !== null && dxStyleLink !== null) {
      // 假如存在id为theme-style 的link标签，直接修改其href
      if (isLight) {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.light.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-light-scheme.css`;
      } else {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.dark.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-dark-scheme.css`;
      }
    } else {
      // 不存在的话，则新建一个
      styleLink = document.createElement('link');
      styleLink.type = 'text/css';
      styleLink.rel = 'stylesheet';
      styleLink.id = 'theme-style';

      dxStyleLink = document.createElement('link');
      dxStyleLink.type = 'text/css';
      dxStyleLink.rel = 'stylesheet';
      dxStyleLink.id = 'dx-theme-style';
      if (isLight) {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.light.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-light-scheme.css`;
      } else {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.dark.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-dark-scheme.css`;
      }
      // styleLink.href = isLight
      //   ? (styleLink.href = `./theme/theme-${colorName}/ant.custom.light.css`)
      //   : (styleLink.href = `./theme/theme-${colorName}/ant.custom.dark.css`);
      document.body.append(styleLink);
      document.body.append(dxStyleLink);
      let bodyClassName = document.body.className;
      bodyClassName += ' dx-theme-generic-typography';
      document.body.className = bodyClassName;
    }
    localStorage.setItem('themeData', colorName);
    localStorage.setItem('themeLight', isLight.toString());
  }

  // window.setup = ({ locale, siderBar, titleBar, projectInfo, primaryColor }) => {
  //   if (locale) {
  //     setLocale(locale, false);
  //   }
  //   if (primaryColor) {
  //     changeTheme(primaryColor);
  //   }
  //   setInitialState((state) => {
  //     return {
  //       ...state,
  //       siderWidth: siderBar ? 208 : 0,
  //       headerHeight: titleBar ? 48 : 0,
  //       projectInfo,
  //     };
  //   });
  // };

  //message.ts webapp配置信息,消息接收相关
  /**
   * 从 localStorge 加载webApp的用户配置
   * @returns WebAppUserConfig
   */
  function getWebAppUserConfigFromLocalStorge() {
    return {
      cpasMainToken: localStorage.getItem('cpasMainToken'), //用户登录凭证，目前可能用不到，由登录页自动登录后系统自己写即可，先留着备用。 可取值：login返回的token值或空
      cpasPrimaryColor: localStorage.getItem('cpasPrimaryColor'), //主题色名称,可取值: red、blue、cyan、green、orange、purple、yellow,默认: red
      themeData: localStorage.getItem('themeData'), //主题色名称,可取值: red、blue、cyan、green、orange、purple、yellow,默认: red
      cpasTheme: localStorage.getItem('cpasTheme'), //"light",//皮肤名称（用于切换暗黑模式）,可取值: light、dark,默认:l ight
      cpasLanguage: localStorage.getItem('cpasLanguage'), //设置当前显示的语言,可取值: en-US、zh-CN,默认: zh-CN
      cpasTitleBar: localStorage.getItem('cpasTitleBar') == 'true', //控制是否显示系统的标题栏（包括系统标题、语言切换、主题色切换、用户卡片等功能）,可取值: true、false,默认: false
      cpasSiderBar: localStorage.getItem('cpasSiderBar') == 'true', //控制是否显示左侧导航边栏,可取值: true、false 默认: true
      cpasApiUrl: localStorage.getItem('cpasApiUrl'), //electron主应用的地址,为web应用请求主应用时提供地址,,可取值:动态的,示例(默认值) http://localhost:8070/cpasApi
      cpasUserInfo: localStorage.getItem('cpasUserInfo')
        ? JSON.parse(localStorage.getItem('cpasUserInfo') || '')
        : {}, // electron主应用的登录后的用户信息,可取值: 动态的, 示例 {"usercode":"201801","username":"刘晓红","rolename":"档案管理员","zw":"经理","ssbmcode":null,"aesPassword":"dLaSXYOlT5xIs+sqL0X2DQ==","loginTime":"2022-05-24 15:53:51"}
    };
  }

  // 2022. 06. 30: DOMLoad不会被正确触发, 改为useEffect.
  /**
   * DOMContentLoaded触发前,localStorage里已存储好了 WebAppUserConfig 中的各项值,按字符串存储的
   * 文档加载完毕时,从 localStorage 中加载并执行设置
   */
  // window.addEventListener('DOMContentLoaded', () => {
  //   setWebAppUserConfig(getWebAppUserConfigFromLocalStorge()); //加载 webAppUserConfig
  // });
  React.useEffect(() => {
    if (isOpenFromPlatform) {
      setWebAppUserConfig(getWebAppUserConfigFromLocalStorge()); //加载 webAppUserConfig
    }
  }, []);

  /**
   * 通过webapp监听message事件,再判断是否存在 cpasPrimaryColor 属性,来验证发送的数据是否是webAppUserConfig,
   * 当您收到此消息收到前,localStorage里已存储好了messageEvent.data中的各项值
   **/
  window.addEventListener(
    'message',
    function (messageEvent) {
      if (
        typeof messageEvent == 'object' &&
        Object.prototype.hasOwnProperty.call(messageEvent.data, 'cpasPrimaryColor')
      ) {
        setWebAppUserConfig(messageEvent.data);
      }
    },
    false,
  );

  /**
   * 通过 webAppUserConfig 配置信息来改写自己的属性值 ,如主题颜色,皮肤,是否显示侧边栏,是否显示标题栏,
   * 各个属性值参考含义参考方法 getWebAppUserConfigFromLocalStorge()
   * 最佳实践: 在webapp的的document.load
   * @param {webapp应用配置} webAppUserConfig
   */
  window.setWebAppUserConfig = function (webAppUserConfig: any) {
    //webapp应用段自己的代码 ,以下是我的示例
    document.body.style.setProperty('--cpasPrimaryColor', webAppUserConfig.cpasPrimaryColor); //设置主题颜色
    document.body.style.setProperty(
      '--siderBar-background-color',
      webAppUserConfig.cpasPrimaryColor,
    ); //侧边背景颜色

    const { cpasLanguage, themeData, cpasTitleBar, cpasSiderBar } = webAppUserConfig;
    console.log('web app user config: ', webAppUserConfig);

    if (cpasLanguage) {
      setLocale(cpasLanguage, true);
    }
    if (themeData) {
      changeTheme(themeData, true);
    }
    setInitialState((state) => {
      return {
        ...state,
        siderWidth: Boolean(cpasSiderBar) ? 208 : 0,
        headerHeight: Boolean(cpasTitleBar) ? 48 : 0,
      };
    });

    // 其他属性设置,并让系统生效
  };

  if (!initialState || !initialState.settings) {
    return null;
  }

  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }
  return (
    <Space className={className} style={{ display: 'none' }}>
      {/* <HeaderSearch
        className={`${styles.action} ${styles.search}`}
        placeholder="站内搜索"
        defaultValue="umi ui"
        options={[
          { label: <a href="https://umijs.org/zh/guide/umi-ui.html">umi ui</a>, value: 'umi ui' },
          {
            label: <a href="/acb">Ant Design</a>,
            value: 'Ant Design',
          },
          {
            label: <a href="https://protable.ant.design/">Pro Table</a>,
            value: 'Pro Table',
          },
          {
            label: <a href="https://prolayout.ant.design/">Pro Layout</a>,
            value: 'Pro Layout',
          },
        ]}
        // onSearch={value => {
        //   console.log('input', value);
        // }}
      /> */}
      {/* <span
        className={styles.action}
        onClick={() => {
          window.open('https://pro.ant.design/docs/getting-started');
        }}
      >
        <QuestionCircleOutlined />
      </span> */}
      <ThemePopover />
      <SelectLang className={styles.action} />
      <Avatar />
    </Space>
  );
};
export default GlobalHeaderRight;
